import React from 'react'
import {Collapse} from 'antd';
import moment from 'moment';
const {Panel} = Collapse;
import {Table, Divider, Tag,message} from 'antd';
import './index.less';
import axios from 'axios';
import {PATH,IP} from '../../../utils/urls';
import {getResourceNameByType} from '../../../utils/config';
import BreadcrumbCustom from '../../../components/BreadcrumbCustom';

//设备列表详细信息
const resourceArray = [];
export default class SoftwareMonitor extends React.Component {
    //设备菜单标题
    columns0 = [
        {
            title: '序号',
            dataIndex: 'number',
            key: 'number',
        },
        {
            title: 'appid',
            dataIndex: 'appid',
            key: 'appid',
        },
        {
            title: 'IP',
            dataIndex: 'IP',
            key: 'IP',
        },
        {
            title: 'CPU利用率',
            key: 'cpu',
            dataIndex: 'cpu',
        },
        {
            title: '内存利用率',
            key: 'storage',
            dataIndex: 'storage',
        },
        {
            title: '硬盘利用率',
            key: 'caliche',
            dataIndex: 'caliche',
        },
        {
            title: '网络IO',
            key: 'network',
            dataIndex: 'network',
        },
        {
            title: '状态',
            key: 'state',
            dataIndex: 'state',
        },
        {
            title: '更新时间',
            key: 'updatetime',
            dataIndex: 'updatetime',
        },
        {
            title: 'Action',
            dataIndex: '',
            key: 'x',
            render: (text,record) => {
                //0未启动，1启动，2未发现
                if(record.stateType ==0 && record.stateType!=""){
                    return <button className="greenBtn" onClick={() => this.hardWareSwitch(0,record.id,33)}>开机</button>
                }else if(record.stateType ==1 ){
                    return <button className="greenBtn" onClick={() => this.hardWareSwitch(0,record.id,34)}>关机</button>
                }else{
                    return ""
                }
            },
        },
    ];
//软件菜单标题
    columns1 = [
        {
            title: 'appid',
            dataIndex: 'appid',
            key: 'appid',
        },
        {
            title: '软件',
            dataIndex: 'software',
            key: 'software',
        },
        {
            title: '类型',
            dataIndex: 'type',
            key: 'type',
        },
        {
            title: 'CPU利用率',
            key: 'cpu',
            dataIndex: 'cpu',
        },
        {
            title: '内存利用率',
            key: 'storage',
            dataIndex: 'storage',
        },
        {
            title: '网络IO',
            key: 'network',
            dataIndex: 'network',
        },
        {
            title: '状态',
            key: 'state',
            dataIndex: 'state',
        },
        {
            title: 'Action',
            key: 'action',
            render: (text, record) => {
                console.log(record);
                //0未启动，1启动，2未发现
                if(record.stateType ==0 && record.stateType!=""){
                    return <button className="greenBtn" onClick={() => this.hardWareSwitch(1,record.id,33)}>启动</button>
                }else if(record.stateType ==1 ){
                    return (
                        <span className="btnDiv">
                            <button className="closeBtn" onClick={() => this.hardWareSwitch(1,record.id,37)}>关闭</button>
                            <button className="reStartBtn" onClick={() => this.hardWareSwitch(2,record.id,38)}>重启</button>
                        </span>
                    )
                }else{
                    return ""
                }
            },
        },
    ];

    componentWillMount() {
        console.log(123);
    }

    constructor(props) {
        super(props);
        this.state = {
            resourceArray: resourceArray,//设备资源列表
            columns0: this.columns0,//设备菜单标题
            columns1: this.columns1,//软件菜单标题
            currentHardIndex: -1,//当前选中设备资源的索引,
            hostname:""//ip地址
        }
        this.onHardSoftListClick = this.onHardSoftListClick.bind(this);
        this.updateHareAndSoftData = this.updateHareAndSoftData.bind(this);
        this.initWebSocket = this.initWebSocket.bind(this);
        this.getTimeByTemp = this.getTimeByTemp.bind(this);
        this.hardWareSwitch = this.hardWareSwitch.bind(this);
        this.ws = null;
        this.lock = false;
    }

    componentDidMount() {
        //获取设备列表
        this.getHardWareResource();
    }

    /**
     * 设备开关机
     * dealTypeDictId:33开机 34关机 35重启机器 36启动服务 37关闭服务 38重启服务
     * isSoftware:0是设备1 是软件
     */
    hardWareSwitch(isSoftware,resourceId,dealTypeDictId){
        axios.post(PATH.warnDeal,{
            dealTypeDictId:dealTypeDictId,
            isSoftware:isSoftware,
            resourceId:resourceId
        }).then(response=>{
            if(response.data.code == 0){
                message.success(response.data.msg)
            }else{
                message.error(response.data.msg)
            }
        });
    }
    /**
     * 获取设备列表
     * @returns
     */
    getHardWareResource() {
        axios.post(PATH.hardwareResource, {})
            .then(response => {
                console.log(response);
                if (response.data.code == 0) {
                    let dataArray = response.data.data;
                    let newResourceArray = [];
                    for (let i = 0; i < dataArray.length; i++) {
                        newResourceArray.push({
                            name: "名称：" + (dataArray[i].resouceName ? dataArray[i].resouceName : "") + "      类型：" + (dataArray[i].resouceType ? getResourceNameByType(dataArray[i].resouceType) : "")
                            , warnstatus: 0
                            , data: [{
                                key: i, number: i
                                , warnstatus: dataArray[i].warnStatus ? dataArray[i].warnStatus : 0
                                , id: dataArray[i].id ? dataArray[i].id : ""
                                , appid: dataArray[i].appId ? dataArray[i].appId : ""
                                , IP: dataArray[i].resouceIp ? dataArray[i].resouceIp : ""
                                , cpu: dataArray[i].cpuRate ? dataArray[i].cpuRate : ""
                                , storage: dataArray[i].memoryRate ? dataArray[i].memoryRate : ""
                                , caliche: dataArray[i].disk ? dataArray[i].disk : ""
                                , network: dataArray[i].io ? dataArray[i].io : ""
                                ,stateType:dataArray[i].serviceStatus ? dataArray[i].serviceStatus : "0"
                                , state: dataArray[i].serviceStatusName ? dataArray[i].serviceStatusName : ""
                                , updatetime: dataArray[i].currentDataTime ? this.getTimeByTemp(parseInt(dataArray[i].currentDataTime)) : ""
                            }]
                        });
                    }
                    this.setState({
                        resourceArray: newResourceArray
                    });
                    //获取默认打开的第一个设备下的软件
                    this.onHardSoftListClick(0);
                    //创建websocket
                    this.initWebSocket();
                }
            });
    }

    /**
     * 设备列表切换回调函数
     * @returns {*}
     */
    onHardSoftListClick(props) {
        //点击当前设置后，获取设备下的软件名称
        if (this.state.resourceArray.length <= 0 || props == null || props == this.state.currentHardIndex) {
            return;
        }
        this.state.currentHardIndex = props;
        if (this.state.resourceArray[props].softList == null ||
            this.state.resourceArray[props].softList.length <= 0) {
            axios.post(PATH.softwareResource, {
                hardwareId: this.state.resourceArray[props].data[0].id
            }).then(response => {
                let dataArray = response.data.data;
                console.log(response);
                let newSoftArray = [];
                for (let i = 0; i < dataArray.length; i++) {
                    newSoftArray.push({
                        key: i, appid: dataArray[i].id,
                        id:dataArray[i].id,
                        software: dataArray[i].resouceName ? dataArray[i].resouceName : "",
                        type: dataArray[i].resouceTypeName ? dataArray[i].resouceTypeName : "",
                        cpu: dataArray[i].cpuRate ? dataArray[i].cpuRate : "",
                        storage: dataArray[i].memoryRate ? dataArray[i].memoryRate : "",
                        network: dataArray[i].io ? dataArray[i].io : "",
                        stateType: dataArray[i].serviceStatus ? dataArray[i].serviceStatus : "0",
                        state: dataArray[i].serviceStatusName ? dataArray[i].serviceStatusName : "",
                    })
                }
                this.state.resourceArray[props].softList = newSoftArray;
                if (!this.lock) {
                    this.setState({
                        resourceArray: this.state.resourceArray
                    })
                }

                console.log(this.state.resourceArray);
            })
        }
    }

    /**
     * 创建websocket，实时获取设备状态
     * @returns {*}
     */
    initWebSocket() {
        let that = this;
        // this.ws = new WebSocket("ws://"+this.state.hostname+"/websocket/resourceMonitor:" + localStorage.getItem("username"));
        this.ws = new WebSocket("ws://"+IP+"/websocket/resourceMonitor:" + localStorage.getItem("username"));
        this.ws.onopen = function (evt) {
            console.log("Connection open ...");
        };

        this.ws.onmessage = function (evt) {
            if (evt.data.indexOf("连接成功") < 0) {
                that.updateHareAndSoftData(JSON.parse(evt.data));
            }
        };

        this.ws.onclose = function (evt) {
            console.log("Connection closed.");
        };
    }

    /**
     * 根据websocket返回的数据，更新设备和软件数据
     * @returns {*}
     */
    updateHareAndSoftData(updateData) {
        console.log(updateData);
        if (updateData.data.hardwareResource != null) {
            let hardwareResource = updateData.data.hardwareResource;
            //更新设备数据
            for (let i = 0; i < this.state.resourceArray.length; i++) {
                if (hardwareResource.id == this.state.resourceArray[i].data[0].id) {
                    this.state.resourceArray[i].data[0].cpu = hardwareResource.cpuRate;
                    this.state.resourceArray[i].data[0].caliche = hardwareResource.disk;
                    this.state.resourceArray[i].data[0].cpu = hardwareResource.io;
                    this.state.resourceArray[i].data[0].storage = hardwareResource.memoryRate;
                    this.state.resourceArray[i].data[0].serviceStatusName = hardwareResource.serviceStatusName;
                }
            }
        }

        if (updateData.data.softwareResourceList != null) {
            let softwareResourceList = updateData.data.softwareResourceList;
            //更新软件数据
            for (let i = 0; i < this.state.resourceArray.length; i++) {
                if (this.state.resourceArray[i].softList != null) {
                    for (let j = 0; j < this.state.resourceArray[i].softList.length; j++) {
                        for (let k = 0; k < softwareResourceList.length; k++) {
                            if (this.state.resourceArray[i].softList[j].appid == softwareResourceList[k].id) {
                                this.state.resourceArray[i].softList[j].cpu = softwareResourceList[k].cpuRate;
                                this.state.resourceArray[i].softList[j].network = softwareResourceList[k].io;
                                this.state.resourceArray[i].softList[j].storage = softwareResourceList[k].memoryRate;
                                this.state.resourceArray[i].softList[j].serviceStatusName = softwareResourceList[k].serviceStatusName;
                            }
                        }
                    }
                }
            }
        }

        if (!this.lock) {
            this.setState({
                resourceArray: this.state.resourceArray
            });
        }
    }

    /**
     * 组件将被卸载
     */
    componentWillUnmount() {
        console.log("跳转");
        this.lock = true;
        //断开websocket
        if(this.ws !=null){
            this.ws.close();
        }
    }

    /**
     * 时间戳转时间格式
     * @returns {*}
     */
    getTimeByTemp(num){
        return moment(num).format('YYYY-MM-DD HH:mm:ss');
    }

    render() {
        if(this.state.hostname == ""){
            this.state.hostname = location.hostname;
        }

        return (
            <div>
                <BreadcrumbCustom first="资源监控" second="软件监控" />

                <Collapse accordion bordered defaultActiveKey={['0']} onChange={this.onHardSoftListClick}>
                    {
                        this.state.resourceArray.map((item, index) => {
                            //正常状态
                            if (item.warnstatus == 0) {
                                return (
                                    <Panel header={item.name} key={index}>
                                        <Table className="tableResource" columns={this.state.columns0}
                                               dataSource={item.data} bordered pagination={false}/>
                                        <Table className="bottomTable tableResource" columns={this.state.columns1}
                                               dataSource={item.softList} bordered pagination={false}/>
                                    </Panel>
                                )
                                //报警状态
                            } else {
                                return (
                                    <Panel className="alarmTable" header={item.name} key={index}>
                                        <div className="alarmClass">
                                            <a>该设备告警，请检查！</a>
                                        </div>
                                        <Table className="tableResource" columns={this.state.columns0}
                                               dataSource={item.data} bordered pagination={false}/>
                                        <Table className="bottomTable tableResource" columns={this.state.columns1}
                                               dataSource={item.softList} bordered pagination={false}/>
                                    </Panel>
                                )
                            }
                        })
                    }
                </Collapse>
            </div>
        )
    }
}